﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using Eg.Core;
namespace Queries
{
    public class ExampleDataCreator
    {
        private readonly ISessionFactory _sessionFactory;

        public ExampleDataCreator(ISessionFactory sessionFactory)
        {
            if (sessionFactory == null)
            {
                throw new ArgumentNullException("sessionFactory is null");
            }
            this._sessionFactory = sessionFactory;
        }

        public void SetUpDatabase()
        {
            using (var session = _sessionFactory.OpenSession())
            {
                using (var tx = session.BeginTransaction())
                {
                    clearDataBase(session);
                    createMovies(session);
                    createBook(session);
                    tx.Commit();
                }
            }
        }

        private static void clearDataBase(ISession session)
        {
            session.CreateQuery("delete from ActorRole").ExecuteUpdate();
            session.CreateQuery("delete from Product").ExecuteUpdate();
        }
        private static void createMovies(ISession session)
        {
            session.Save(new Movie
            {
                Name = "Raiders of the lost Ark",
                Description = "Awesome",
                UnitPrice = 9.59M,
                Director = "Steven Spielberg",
                Actors = new List<ActorRole>() 
                {
                    new ActorRole(){Actor = "Harrison Ford",Role = "Indiana Jones"}
                }

            }
            );

            session.Save(new Movie
            {
                Name = "The Bucket List",
                Description = "Good",
                UnitPrice = 15M,
                Director = "Rob Reiner",
                Actors = new List<ActorRole>() 
                {
                    new ActorRole(){Actor = "Jack Nicholson",Role = "Edward Cole"},
                    new ActorRole(){Actor = "Morgan Freeman",Role = "Carter Chambers"}
                }
            }
                );
        }
        private static void createBook(ISession session)
        {
            session.Save(new Book { 
                Name="NHibernate 3.0 Cookbook",
                Description = "NHibernate Examples",
                UnitPrice = 50M,
                Author = "Jason Dentler",
                ISBN="978-1-149-513"
            });
        }
    }
}
